#if UNITY_WEBGL 
using System;
using System.IO;
using System.Text;
using UnityEngine;
using WeChatWASM;

[FM_Mono.IgnoreGen]
public class WechatFileStream:Stream
{
    private WXFileSystemManager _fs;
    private int _fd;
    private int _length;
    
    public WechatFileStream(WXFileSystemManager fs, int fd, int length)
    {
        _fs = fs;
        _fd = fd;
        _length = length;
    }
    
    public override void Flush()
    {
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        if (_fd < 0)
        {
            throw new Exception("Stream is closed");
        }
        int bytesRead = _fs.ReadSync(_fd, buffer, offset, count, (int)Position);
        Position += bytesRead;
        return bytesRead;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        switch (origin)
        {
            case SeekOrigin.Current:
                Position += offset;
                break;
            case SeekOrigin.Begin:
                Position = offset;
                break;
            case SeekOrigin.End:
                Position = Length + offset;
                break;
        }

        return Position;
    }

    public override void SetLength(long value)
    {
        _length = (int)value;
        _fs.FTruncateSync(_fd, (int)value);
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        int writeBytes = _fs.WriteSync(_fd, buffer, offset, count, (int) Position);
        Position += writeBytes;
    }

    public override void Close()
    {
        _fs.CloseFileSync(_fd);
        _fd = -1;
        base.Close();
    }

    public override bool CanRead
    {
        get
        {
            return true;
        }
    }

    public override bool CanSeek
    {
        get
        {
            return true;
        }
    }

    public override bool CanWrite
    {
        get
        {
            return true;
        }
    }

    public override long Length
    {
        get
        {
            return _length;
        }
    }
    public override long Position { get; set; }
}
#endif